package com.abbcc.module.admin;

import java.util.Date;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.envers.Audited;
import org.springframework.beans.factory.annotation.Autowired;

import com.abbcc.action.BaseAction;
import com.abbcc.common.CommonConst;
import com.abbcc.models.TdAdmin;
import com.abbcc.models.TdUser;
import com.abbcc.service.AdminService;
import com.abbcc.service.UserService;
import com.abbcc.util.StringUtil;

public class AdminAction extends BaseAction<TdAdmin> {
	@Autowired
	private AdminService adminService;
	@Autowired
	private UserService userService;
	public String oldPsw;
	public String loginType;

	public String login() {
			if (StringUtil.isNotBlank(entity.getUsername())
					&& StringUtil.isNotBlank(entity.getPassword())) {
				List<TdAdmin> list = adminService.findByExample(entity);
				if (list.isEmpty()) {
					TdAdmin td = new TdAdmin();
					td.setUsername(entity.getUsername());
					if (adminService.findByExample(td).isEmpty())
						result = "无此用户!";
					else
						result = "密码错误!";
					loginType = "admin";
					if (getCurrentAdmin() != null)
						saveLog(entity.getUsername(), result,
								CommonConst.LOGLOGIN,
								CommonConst.LOGTYPEBYADMIN);
					return INPUT;
				} else {
					getSession().setAttribute(CommonConst.SESSIONADMIN,
							list.get(0));
					saveLog(entity.getUsername(), "登陆成功!",
							CommonConst.LOGLOGIN, CommonConst.LOGTYPEBYADMIN);
					return SUCCESS;
				}
			} else {
				result = "用户名或密码不能为空!";
				return INPUT;
			}
	}

	public String loginout() {
		if (getCurrentAdmin() != null)
			saveLog(entity.getUsername(), "退出成功!", CommonConst.LOGLOGOUT,
					CommonConst.LOGTYPEBYADMIN);
		this.getSession().invalidate();
		loginType = "admin";
		return INPUT;
	}

	public String updatePsw() {
		if (StringUtil.isNotBlank(oldPsw)
				&& StringUtil.isNotBlank(entity.getPassword())) {
			if (oldPsw.equals(getCurrentAdmin().getPassword())) {
				getCurrentAdmin().setPassword(entity.getPassword());
				adminService.saveOrUpdate(getCurrentAdmin());
				reloadSession(CommonConst.SESSIONADMIN, getCurrentAdmin());
				result = "修改成功!";
				saveLog("密码", result, CommonConst.LOGUPDATE,
						CommonConst.LOGTYPEBYADMIN);
			} else {
				result = "原密码不正确";
				saveLog("密码", result, CommonConst.LOGUPDATE,
						CommonConst.LOGTYPEBYADMIN);
			}
		}
		return JSON;
	}

	public String getLoginType() {
		return loginType;
	}

	public void setLoginType(String loginType) {
		this.loginType = loginType;
	}

}
